local skynet = require 'skynet'
require 'skynet.manager'

-- local dbg = require('emmy_core')
-- dbg.tcpListen('localhost', 9966)

require 'nggs.base.const'
local log = require 'nggs.base.log'
local nmath = require 'nggs.base.math'
local inspect = require 'nggs.base.inspect'

local Class = require 'nggs.base.class'

local Test = Class('test4')

local playerDBMark = 100

local function getPlayerDB(playerID)
    return nmath.Floor(playerID % playerDBMark)
end

function Test:Constructor()
    self._hashDB = {}
    self._nextDB = 0
end

function Test:getDBMaxID(index)
    return self._hashDB[index] or 0
end

function Test:hashPlayerID(playerID)
    local index = getPlayerDB(playerID)
    self._hashDB[index] = self._hashDB[index] or 0

    local id = nmath.Floor(playerID / playerDBMark)
    if id > self._hashDB[index] then
        self._hashDB[index] = id
    end
end

function Test:GetNewPlayerID()
    local maxID = self:getDBMaxID(self._nextDB)
    local newID = nmath.Floor((maxID + 1) * playerDBMark + self._nextDB)
    self._nextDB = self._nextDB + 1
    if self._nextDB >= 1 then
        self._nextDB = 0
    end
    self:hashPlayerID(newID)
    return newID
end

skynet.error('test4 started')

skynet.start(
    function()
        -- skynet.timeout(
        --     300,
        --     function()
        --         skynet.error("test4 end")
        --         skynet.sleep(0)
        --         skynet.abort()
        --     end
        -- )

        local t = Test.New()
        for i = 1, 10000 do
            local playerID = t:GetNewPlayerID()
            log.Printf('playerID=%d', playerID)
        end
    end
)
